
const db = require('../db');

const express = require('express');
const router = express.Router();

//服务端获取FormData类型的数据，需要使用第三方模块 [multer]
const multer = require('multer');
//配置上传文件路径
const upload = multer({ dest: 'uploads/' });
//配置发布时间需要用第三方模块monent
const moment = require('moment');
const { post } = require('./login');

//------------------------分页获取文章接口--------------------------
router.get('/list', (req, res) => {
    //console.log(req.query);
    // 设置变量，接收请求参数
    let { pagenum, pagesize, cate_id, state } = req.query;
    // console.log(cate_id, state);
    // 根据cate_id 和 state制作SQL语句的条件
    let w = '';
    if (cate_id) {
        w += ` and cate_id=${cate_id} `;
    }
    if (state) {
        w += ` and state='${state}' `;
    }
    // 分页查询数据的SQL（该SQL用到了连表查询，并且使用了很多变量组合）
    let sql1 = `select a.id, a.title, a.state, a.pub_date, c.name cate_name from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}
    limit ${(pagenum - 1) * pagesize}, ${pagesize}`;
    // 查询总记录数的SQL，查询条件和前面查询数据的条件 必须要一致
    let sql2 = `select count(*) total from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}`;
    // 分别执行两条SQL（因为db查询数据库是异步方法，必须嵌套查询）
    db(sql1, (err, result1) => {
        //console.log(result1);
        if (err) throw err;
        db(sql2, (e, result2) => {
            if (e) throw e;
            res.send({
                status: 0,
                message: '获取文章列表数据成功',
                data: result1,
                total: result2[0].total
            });
        })
    })
});
//-------------------------添加文章接口----------------------------
router.post('/add', upload.single('cover_img'), (req, res) => {
    let { title, content, cate_id, state } = req.body;

    let pub_date = moment().format('YYYY-MM-DD HH:mm:ss');
    console.log(req.file.filename);
    let cover_img = req.file.filename;
    let author_id = req.user.id;

    let sql = `insert into article set title='${title}',content='${content}',cate_id=${cate_id},state='${state}',pub_date='${pub_date}',cover_img='${cover_img}',author_id=${author_id}`;
    db(sql, (err, result) => {
        if (err) throw err;
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '发布成功' })
        } else {
            res.send({ status: 1, message: '发布失败' })
        }
    });
});
//---------------------------删除文章接口-------------------------
router.get('/delete/:id', (req, res) => {
    // 怎么获取url中的参数，答，使用express提供的 req.params
    console.log(req.params.id);
    let id = req.params.id;
    let sql = `update article set is_delete=1 where id=${id} and author_id=${req.user.id}`;
    db(sql, (err, result) => {
        if (err) throw err;
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '删除成功' })
        } else {
            res.send({ status: 1, message: '删除失败' })
        }
    });
})
//--------------------------更新文章接口--------------------------
router.post('/update', upload.single('cover_img'), (req, res) => {
    let { title, cate_id, state, content, id } = req.body;
    let cover_img = req.file.filename;

    let sql = `update article set title='${title}', content='${content}', cate_id=${cate_id}, state='${state}', cover_img='${cover_img}' where id=${id}`;
    db(sql, (err, result) => {
        if (err) throw err;
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '修改文章成功' })
        } else {
            res.send({ status: 1, message: '修改文章失败' })
        }
    })

})

//-----------------------根据id获取一篇文章接口-------------------
router.get('/:id',(req,res)=>{
    console.log(req.params.id);
    db(`select * from article where id=${req.params.id}`,(err,result)=>{
        if(err)throw err;
        res.send({state:0,message:'获取文章成功',data:result[0]})
    })
})
module.exports = router;